package com.dk.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dk.mapper.ABookMapper;
import com.dk.pojo.ABook;
import com.dk.pojo.ABookExample;
import com.dk.service.ABookServiceI;
import constant.RedisNewsConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ABookServiceImpl implements ABookServiceI {

    @Autowired
    private ABookMapper aBookMapper;


    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public List<ABook> getInfoServer() {
        //如果查询 判断redis里面有没有这个key
        if(!redisTemplate.hasKey(RedisNewsConst.ABooks)){
            //那么查询数据库
            List<ABook> list = aBookMapper.getInfoServer();
            //遍历数据库查询所有数据 set给redis，list转为String放redis
            for(ABook aBook1 : list){
                redisTemplate.boundHashOps(RedisNewsConst.ABooks).put(aBook1.getBookId(),JSON.toJSONString(aBook1));
            }
            return list;
        }else {
            //如果redis里面有这个key，获取值
            List<Object> list = redisTemplate.boundHashOps(RedisNewsConst.ABooks).values();
            //定义一个list集合
            List<ABook> aBooks = new ArrayList<>();
            //遍历redis里面所有数据转为String
            for(Object o : list){
                //把String再转为list返回过去
                aBooks.add(JSON.parseObject((String)o,ABook.class));
            }
            return aBooks;
        }
    }

    @Override
    public void saveById(ABook aBook) {
        aBookMapper.insertSelective(aBook);
        redisTemplate.delete(RedisNewsConst.ABooks);
    }

    @Override
    public ABook getUpdateInfo(Integer bookId) {
        //根据id查询reidsk数据
        //查询出来是object类型,转为String类型，通过JSONObject.parseObject 转为实体类
        String o = (String)redisTemplate.boundHashOps(RedisNewsConst.ABooks).get(bookId);
        ABook aBook = JSONObject.parseObject(o,ABook.class);
        return aBook;
    }

    @Override
    public void updateById(ABook aBook) {
        aBookMapper.updateByPrimaryKeySelective(aBook);
        redisTemplate.delete(RedisNewsConst.ABooks);
    }

    @Override
    public void deleteById(Integer bookId) {
        aBookMapper.deleteByPrimaryKey(bookId);
        redisTemplate.boundHashOps(RedisNewsConst.ABooks).delete(bookId);

    }
}
